package org.example.utils;

/**
 * @author lwc
 * @description: TODO
 * @date 2023/12/22 17:43
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {
    // 数据库连接参数
    private static final String URL = "jdbc:mysql://localhost:3306/test";
    private static final String USER = "root";
    private static final String PASSWORD = "9XME3z94xs9nhCj";

    // 获取数据库连接
    public static Connection getConnection(String url,String username,String password) {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    // 关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 执行查询操作
    public static ResultSet executeQuery(Connection connection, String sql) {
        ResultSet resultSet = null;
        try {
            Statement statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    // 执行更新操作（如 INSERT、UPDATE、DELETE）
    public static int executeUpdate(Connection connection, String sql) {
        int result = 0;
        try {
            Statement statement = connection.createStatement();
            result = statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        // 示例：查询数据库中的所有用户
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test",USER,PASSWORD);
        ResultSet resultSet = JDBCUtils.executeQuery(connection, "SELECT * FROM users");
        try {
            while (resultSet.next()) {
                System.out.println(resultSet.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, null, resultSet);
        }
    }
}
